package com.haogu.service.impl;

import com.haogu.entity.Customer;
import com.haogu.entity.Leads;
import com.haogu.entity.TaskPrompt;
import com.haogu.entity.User;
import com.haogu.mapper.TaskMapper;
import com.haogu.mapper.UserMapper;
import com.haogu.service.CustomersService;
import com.haogu.service.LeadsService;
import com.haogu.service.ScheduledTask;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ScheduledTaskImpl implements ScheduledTask {
    @Resource
    private LeadsService leadsService;
    @Resource
    private CustomersService customersService;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private UserMapper userMapper;
    @Override
//    @Scheduled(cron="0/10 * * * * ?")
    public void putLeadsChi() {
        List<Leads> leads = leadsService.selectLeadsIsDrawNoTranformd();
        for(Leads l : leads){
            long now = new Date().getTime()/1000;
            long last = l.getHaveTime().getTime()/1000;
            long guiDing = 60*60*24*7;
            if((now-last)>guiDing){
                leadsService.updateOwnerUserId(l.getId(),null);
            }
        }
    }

    /**
     * 定时将没有维护的客户放入到客户池
     */
//    @Scheduled(cron="0/10 * * * * ?")
    public void recallCustomerPool() {
        List<Customer> customers = customersService.customerPool();
        for (Customer c : customers) {
            long now = new Date().getTime()/1000;//当前时间
            long last = c.getUpdateTime().getTime()/1000;//获取客户更新后的时间
            long guiDing = 60*60*24*7;//规定时间
            //超过规定时间将客户放入客户池
            if((now-last)>guiDing){
                customersService.toReleaseCustomers(c.getId());
            }
        }
    }
    /**
     * 任务截止提醒
     */
//    @Scheduled(cron = "* */5 * * * ?")
    public void taskTiXing(){
        User user = userMapper.selectUserByUserId(1);
        List<TaskPrompt> taskPrompts = taskMapper.taskTiXing();
        //主题
        String subject = "";
        //内容
        String context = "";
        for(TaskPrompt tp : taskPrompts){
            subject = tp.getSubject() + "任务提醒";
            if(tp.getDiff()>0){
                context = "你的" + tp.getSubject() + "任务截止时间已过，请尽快完成任务。";
            }else{
                String temp = Math.abs(tp.getDiff())==0?"今":"还有"+Math.abs(tp.getDiff());
                context = "你的" + tp.getSubject() + "任务" + temp + "天结束，请尽快完成任务。" ;
            }
            customersService.sendSimpleMail(user.getEmail(),tp.getEmail(),subject,context);
        }

    }
}
